/*** Class Name: IfulfillFulfillmentItemEmailHandler 
 * Author: Accenture
 * Date: 13-Sep-2011
 * Requirement/Project Name: iFulfill
 * Requirement Description: Handles incoming email for Fulfillment Items
 **/
 
global class IfulfullFulfillmentItemEmailHandler implements Messaging.InboundEmailHandler {

   /*
    *  Handles the inbound e-mail.
    *
    **/
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope env) 
  {
         System.debug (' Enter the class IfulfullFulfillmentItemEmailHandler  handleInboundEmail method');
         Messaging.InboundEmailResult result = new Messaging.InboundEmailresult(); 
         String txt =email.subject;
         String fiName = null;
         Integer startIndex = null;
         Integer endIndex = null;
         boolean found = false; 
         Pattern emailPattern = Pattern.compile(IfullfillTextConstant.FI_NAME_PATTERN);
         Matcher emailMatcher = emailPattern.matcher(txt);

         // Searching the Subject  for Fulfillment Item name Pattern 
         if( txt!= null && emailMatcher.find())
         {
             found = true;
             startIndex = emailMatcher.start();
             endIndex = emailMatcher.end();
             fiName =txt.substring(startIndex,endIndex );
          
         }
         else
         {
            // Searching the mail message  for Fulfillment Item name Pattern 
             txt = email.plainTextBody;
             emailMatcher = emailPattern.matcher(txt);
             if( txt!= null && emailMatcher.find())
             {
                found = true;
                startIndex = emailMatcher.start();
                endIndex = emailMatcher.end();
                fiName =txt.substring(startIndex,endIndex );
               
             }              
         }
          if(found)
         {
                insertTask(fiName ,email);
         }
         else
         {
            System.debug('Fulfillment Item name Pattern not found ');
         }
         return result;
    }
    
   /*
    * Insert the task if FI name match is found.
    *
    **/      
    public void insertTask(String fiName , Messaging.InboundEmail email )
    {
             
        List <Task> taskList= new List<Task>();
        List <Attachment> attachmentList ;
        Task newTask;
        List<Fullfilment_Item__c>  fulFillItemList =[select id, ownerid  from Fullfilment_Item__c  where Name = :fiName.trim() ];                     
        RecordTypeIDs__c listViewIDObj = RecordTypeIDs__c.getInstance(userinfo.getProfileId());
      
        if(fulFillItemList.size() > 0 )
        {
            String ownerID = fulFillItemList.get(0).ownerid;
            newTask = new Task(
                                   RecordTypeID = listViewIDObj.IFulfillTaskRecordType__c,
                                   Description = email.plainTextBody ,
                                   Priority = 'Normal',
                                   Status = ' Not Started',
                                   Subject = email.subject,
                                   ReminderDateTime = System.now(),
                                   WhatId = fulFillItemList.get(0).id);      
                                      
           // Check the FI object  owner is queue or  user                  
           if(ownerID.startsWith(IfullfillTextConstant.USER_ID_STARTS_WITH))
           {
               newTask.OwnerID = ownerID;
           }
           else
           {
               //Fulfillment item owner is Queue
                System.debug ('Fulfillment item owner is Queue');                                 
           }
           taskList.add(newTask); 
           
           try
           {   
                if(taskList.size()> 0)
                {
                    insert taskList;
                    attachmentList = processEmailAttachment(email,taskList);
                    if(attachmentList !=null && attachmentList.size() > 0 )
                    {
                        insert attachmentList;
                    }
                }  
            }
            catch(DMLException ex)
            {
                GeneralConstants.mailAnyExceptionToMe('IfulfullFulfillmentItemEmailHandler ','insertTask',ex);
                System.debug('Task insertion failed '+ ex );
            }
            catch(Exception e)
            {
                GeneralConstants.mailAnyExceptionToMe('IfulfullFulfillmentItemEmailHandler ','insertTask',e);
                System.debug('Task insertion failed '+ e );
            }                       
        }
        else
        {
            System.debug('invalid Fulfillment Item name ' + fiName );
        } 
    }
     
    /*
    * Process any attchment if peresent in  inbound email.
    *
    **/ 
    
    private List<Attachment> processEmailAttachment( Messaging.InboundEmail email, List<Task> taskList)
    {
        List <Attachment> attachmentList = new List<Attachment>();
        List <Task> tempTaskList = [Select id,ownerID  from Task where id = : taskList.get(0).id]; 
        if(tempTaskList.size() > 0)
        {
             // Check if we have any text attachment                       
             if (email.textAttachments!= null && email.textAttachments.size() > 0) 
             {
                 for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) 
                 {
                     Attachment attachment = new Attachment();
                     attachment.Name = tAttachment.fileName;
                     attachment.Body = Blob.valueOf(tAttachment.body);
                     attachment.ParentId = tempTaskList.get(0).id;
                     attachment.ownerId = tempTaskList.get(0).ownerid;
                     attachmentList.add(attachment); 
                     
                 }
             }
             // Check if any binary attachment are present.            
             if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) 
             {
                   System.debug ('Receviced mail with  attachment');      
                   for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) 
                   {
                       Attachment attachment = new Attachment();
                       // attach to the newly created contact record
                       attachment.Name = email.binaryAttachments[i].filename;
                       attachment.Body = email.binaryAttachments[i].body;
                       attachment.ParentId = tempTaskList.get(0).id;
                       attachment.ownerId = tempTaskList.get(0).ownerid;
                       attachmentList.add(attachment); 
                   }     
              }        
         }
         return attachmentList;
     }               
}